package ar.com.photo_admin.service.security

import ar.com.photo_admin.domain.Event
import ar.com.photo_admin.domain.EventAlbumToken

import java.util.List;

/**
 * Service for domain class EventAlbumToken
 */
class EventAlbumTokenService {

	def tokenGeneratorService
	
	/**
	 * Generates a token for the given event and the set of albums.
	 */
	def generateToken(Event event, Set tokenAlbums) {
		
		def token = tokenGeneratorService.generateTokenOfList([event, tokenAlbums])
		def eventAlbumToken = EventAlbumToken.findByToken(token)
		
		return eventAlbumToken ? generateToken(event, tokenAlbums) : token		
	}
	
	/**
	 * Checks whether the token exists in the database.
	 */
	def tokenExists(tokenSt) {
		return EventAlbumToken.findByToken(tokenSt) != null
	}
	
	/**
	 * Checks whether the token grants permission to the given album.
	 */
	def tokenGrantsPermissionToAlbum(tokenSt, albumId) {
		EventAlbumToken token = EventAlbumToken.findByToken(tokenSt);		
		return token.albums.any { it.id.toString() == albumId.toString() } 
	}
	
	/**
	 * Gets the event related to the given token.
	 */
	def getEventFromToken(tokenSt) {
		EventAlbumToken token = EventAlbumToken.findByToken(tokenSt);		
		return token.albums.size() > 0 ? token.albums.find { true }.event : null
	}
}
